package cn.zch.soft.util.process.wcmd;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.logging.Logger;
/**
 * @author ge'yong'liang
 */
@Slf4j
public class CheckProcessToKillByCmd {
  public static final Logger logger = Logger.getLogger(CheckProcessToKillByCmd.class.getName());
  public static void main(String[] args) {
    //模糊匹配谷歌进程
    String prefix = "进程名";
    CheckProcessToKillByCmd.comFirmSingleProcess(prefix);
  }
  /**
   * 确认进程,获取进程,杀死进程
   *
   * @param prefix 进程名前缀
   */
  public static void comFirmSingleProcess(String prefix) {
    if (prefix == null) {
      throw new NullPointerException("The prefix is null,please check it!!");
    }
    // 声明文件读取流
    BufferedReader out = null;
    BufferedReader br = null;
    try {
      // 创建系统进程
      ProcessBuilder pb = new ProcessBuilder("tasklist");
      Process p = pb.start();
      // 读取进程信息
      out = new BufferedReader(new InputStreamReader(new BufferedInputStream(p.getInputStream()), Charset.forName("GB2312")));
      br = new BufferedReader(new InputStreamReader(new BufferedInputStream(p.getErrorStream())));
      // 创建集合 存放 进程+pid
      List<String> list = new ArrayList<>();
      // 读取
      String outStr;
      while ((outStr = out.readLine()) != null) {
        // 将读取的进程信息存入集合
        list.add(outStr);
      }
      // 遍历所有进程
      for (int i = 3; i < list.size(); i++) {
        // 必须写死,截取长度,因为是固定的
        // 进程名
        String process = list.get(i).substring(0, 25).trim();
        // 进程号
        String pid = list.get(i).substring(25, 35).trim();
        String processInfo = String.format("process:%s pid:%s", process, pid);
        if (process.toLowerCase(Locale.ROOT).contains("java")) {
          log.info(processInfo);
        }
        // 匹配指定的进程名,若匹配到,则立即杀死
        if (process.startsWith(prefix)) {
          Runtime.getRuntime().exec("taskkill /F /PID " + pid);
        }
      }
      // 若有错误信息 即打印日志
      String line = br.readLine();
      if (line != null) {
        logger.info(line);
      }
    }
    catch (IOException e) {
      e.printStackTrace();
    }
    finally {
      // 关流
      try {
        if (out != null) {
          out.close();
        }
      }
      catch (IOException e) {
        e.printStackTrace();
      }
      try {
        if (br != null) {
          br.close();
        }
      }
      catch (IOException e) {
        e.printStackTrace();
      }
    }
    //    try ( FileReader fr = new FileReader(fileName); BufferedReader br = new BufferedReader(fr) )
    //    { return br.readLine(); } catch (...) {}
    //
    // try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
    //    // no need to name intermediate resources if you don't want to return br.readLine(); } catch (...) {}
    //  }
  }
}
